package com.wu.webflux6.sms;

import java.util.Map;

import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

import reactor.core.publisher.Mono;

public class SmsReactiveAuthenticationManager implements ReactiveAuthenticationManager{
	private final ReactiveUserDetailsService userDetailsService;
	
	private PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
	
	public SmsReactiveAuthenticationManager(ReactiveUserDetailsService userDetailsService) {
		Assert.notNull(userDetailsService, "userDetailsService cannot be null");
		this.userDetailsService = userDetailsService;
	}
	@Override
	public Mono<Authentication> authenticate(Authentication authentication) {
		if(authentication.getName().equals("bad")) {
			return Mono.empty();
		}
		if(authentication instanceof SmsCodeAuthenticationToken) {
			
			//前端传入的
			final String username = authentication.getName();
			final String presentedPassword = (String) authentication.getCredentials();
			//数据库的
			Mono<UserDetails> findByUsername = this.userDetailsService.findByUsername(username);
			//session里的
			Map<String, String> concurrentHashMap = ((SmsCodeAuthenticationToken) authentication).getConcurrentHashMap();
			final String phone =concurrentHashMap.get("phone");
			final String code=concurrentHashMap.get("smscode");
			final Object sessionCodeTime=concurrentHashMap.get("createTime");
//			final String phone = ((SmsCodeAuthenticationToken) authentication).getSessionPhone();
//			final String code = ((SmsCodeAuthenticationToken) authentication).getSessionSMSCode();
//			final Object sessionCodeTime = ((SmsCodeAuthenticationToken) authentication).getSessionCodeTime();
			//TODO 比较验证
			
			return findByUsername.map(u -> new SmsCodeAuthenticationToken(u, u.getPassword(), u.getAuthorities()));
		}else {
			return Mono.empty();
		}
		
		
		
		
//		String password = findByUsername.block().getPassword();
//		boolean matches = this.passwordEncoder.matches(presentedPassword, password);		
//		if(matches) {
//			return findByUsername.map(u -> new SmsCodeAuthenticationToken(u, u.getPassword(), u.getAuthorities()));
//		}
//		
//		return Mono.empty();
	}
	
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
		this.passwordEncoder = passwordEncoder;
	}

}
